var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var fs = require('fs');
var port = process.env.PORT || 3000;
var app = express();

var dbUrl = "mongodb://localhost/nodeTest";
mongoose.connect(dbUrl);

var models_path = __dirname + '/app/models';
var walk = function (path) {
    fs
        .readdirSync(path)
        .forEach(function (file) {
            var newPath = path + '/' + file;
            var stat = fs.statSync(newPath);

            if (stat.isFile()) {
                if (/(.*)\.(js|coffee)/.test(file)) {
                    require(newPath);
                }
            } else if (stat.isDirectory()) {
                walk(newPath)
            }
        })
};
walk(models_path);
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var logger = require('morgan');
var multipart = require('connect-multiparty');
app.set("views", "./app/views/pages");
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(session({
    secret: "imooc",
    store: new mongoStore({
        url: dbUrl,
        collection: 'sessions'
    })
}));
app.use(multipart());

if ('development' === app.get('env')) {
    app.set("showStackError", true);
    app.use(logger(':method :url :status'));
    app.locals.pretty = true;
    mongoose.set("debug", true);
}

require('./config/routes')(app);

app.use(express.static(path.join(__dirname, 'public')));
app.locals.moment = require("moment");
app.listen(port);

console.log("server start at " + port);
